﻿using System;
using System.Configuration;
using mojoPortal.Net;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using ud_gSDMS.Code_Service;
using mojoPortal.Business.WebHelpers;
using System.IO;
using Brettle.Web.NeatUpload;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.UI;
namespace ud_gSDMS.contract
{
    public partial class Contract_Edit : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private string id;
        private SiteUser _siteUser;
        protected String cacheDependencyKey;

        void Page_Load(object sender, EventArgs e)
        {
            //if (!UserCanEditPage() || !UserCanViewPage())
            //{
            //    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            //}

            _siteUser = SiteUtils.GetCurrentSiteUser();

            //SiteUser.ConfirmRegistration()
            if (_siteUser == null)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }

            

            if (!Page.IsPostBack)
            {
                PopulateLabels();
                PopulateControls();
                if (!string.IsNullOrEmpty(id))
                {
                    LoadData(id);
                }
            }
        }
        private void PopulateLabels()
        {

        }
        private void PopulateControls()
        {
            if (string.IsNullOrEmpty(id))
            {
                txtContract_Code.Text = gSDMS_BL.ud_gSDMS_CONTRACT_AutoGenCode();
            }
            var db = new gSDMS_DataLinq();

            var minDay = Convert.ToDateTime(ConfigurationManager.AppSettings["MinDay"]);
            var maxDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
            datContract_Date.MinDate = minDay;
            datContract_Date.MaxDate = maxDay;

            datStart_Date.MinDate = minDay;
            datStart_Date.MaxDate = new DateTime(maxDay.Year + 1, maxDay.Month, maxDay.Day);

            datEnd_Date.MaxDate = minDay;
            datEnd_Date.MaxDate = new DateTime(maxDay.Year + 1, maxDay.Month, maxDay.Day);


            cboCat_Product_Package_ID.DataValueField = "CAT_Product_Package_ID";
            cboCat_Product_Package_ID.DataTextField = "Name";
            cboCat_Product_Package_ID.DataSource = Library.LINQToDataTable(db, db.ud_gSDMS_CAT_PRODUCT_PACKAGEs);
            cboCat_Product_Package_ID.DataBind();

            cboAccount_Manager.DataValueField = "UserID";
            cboAccount_Manager.DataTextField = "LoginName";
            cboAccount_Manager.DataSource = gSDMS_BL.mp_User_Search(null, null, null, null, null, null, "6");
            cboAccount_Manager.DataBind();
            if (_siteUser != null) cboAccount_Manager.SelectedValue = _siteUser.UserId.ToString();

            cboAssigned_To.DataValueField = "UserID";
            cboAssigned_To.DataTextField = "LoginName";
            cboAssigned_To.DataSource = gSDMS_BL.mp_User_Search(null, null, null, null, null, null, "12");
            cboAssigned_To.DataBind();
            //if (_siteUser != null) cboAssigned_To.SelectedValue = _siteUser.UserId.ToString(); //Vo ly

            var status = gSDMS_BL.ud_gSDMS_CAT_CONTRACT_STATUS_Get(0, "Not Accepted");
            cboCAT_Contract_Status_ID.Items.Add(new Telerik.Web.UI.RadComboBoxItem(status.Name , status.CAT_Contract_Status_ID.ToString()));
            cboCAT_Contract_Status_ID.SelectedValue = status.CAT_Contract_Status_ID.ToString();

            txtNotes.WebEditor.ToolBar = mojoPortal.Web.Editor.ToolBar.Full;
            txtNotes.WebEditor.Height = 200;

        }

        private void LoadData(string id)
        {
            if (string.IsNullOrEmpty(id)) return;
            if (_siteUser == null) return;
            var o = gSDMS_BL.ud_gSDMS_CONTRACT_Get(id);
            if (o != null)
            {
                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "12|14|1") == false)
                {
                    if (o.Account_Manager != _siteUser.UserId)
                    {
                        WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                    }
                }

                hidId.Value = o.Contract_ID.ToString();
                if (o.CreatedOn != null) hidCreatedOn.Value = o.CreatedOn.Value.ToString();
                txtContract_Code.Text = o.Contract_Code;
                txtContract_Name.Text = o.Contract_Name;
                datContract_Date.SelectedDate = o.Contract_Date;
                cboCat_Product_Package_ID.SelectedValue = o.Cat_Product_Package_ID.ToString();
                if (o.Start_Date != null) datStart_Date.SelectedDate = o.Start_Date;
                if (o.End_Date != null) datEnd_Date.SelectedDate = o.End_Date;
                txtResource.Text = o.Resource.ToString();
                txtCustomer_Code.Text = o.Customer_Code;
                txtCustomer_Name.Text = o.Customer_Name;
                txtCustomer_Phone.Text = o.Customer_Phone;
                txtCustomer_Fax.Text = o.Customer_Fax;
                txtCustomer_Email.Text = o.Customer_Email;
                txtContact_Name_1.Text = o.Contact_Name_1;
                txtContact_Email_1.Text = o.Contact_Email_1;
                txtContact_Phone_1.Text = o.Contact_Phone_1;
                txtContact_Name_2.Text = o.Contact_Name_2;
                txtContact_Email_2.Text = o.Contact_Email_2;
                txtContact_Phone_2.Text = o.Contact_Phone_2;
                txtCompany_Address.Text = o.Customer_Address;

                if (o.Account_Manager != null) cboAccount_Manager.SelectedValue = o.Account_Manager.Value.ToString();
                if (o.Assigned_To != null) cboAssigned_To.SelectedValue = o.Assigned_To.Value.ToString();
                txtNotes.Text = o.Notes;
                if (o.CAT_Contract_Status_ID != null)
                    cboCAT_Contract_Status_ID.SelectedValue = o.CAT_Contract_Status_ID.Value.ToString();

                chkActive.Checked = o.Active;
                btnUpload.Visible = true;
                BindAttachments();
            }
        }

        #region event
        void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                    bool isUpload = hidId.Value == ""; 
                    string hidID = hidId.Value;
                    var userSite = SiteUtils.GetCurrentSiteUser();
                    gSDMS_BL.ud_gSDMS_CONTRACT_Upd(ref hidID, txtContract_Code.Text, txtContract_Name.Text,
                                                   datContract_Date.SelectedDate != null ? datContract_Date.SelectedDate.Value.ToShortDateString() : null,
                                                   cboCat_Product_Package_ID.SelectedValue,
                                                   datStart_Date.SelectedDate != null ? datStart_Date.SelectedDate.Value.ToShortDateString() : null,
                                                   datEnd_Date.SelectedDate != null ? datEnd_Date.SelectedDate.Value.ToShortDateString() : null,
                                                   txtResource.Text, txtCustomer_Code.Text, txtCustomer_Name.Text,
                                                   txtCustomer_Phone.Text, txtCustomer_Fax.Text, txtCustomer_Email.Text, txtCompany_Address.Text,
                                                   txtContact_Name_1.Text, txtContact_Email_1.Text, txtContact_Phone_1.Text,
                                                   txtContact_Name_2.Text, txtContact_Email_2.Text, txtContact_Phone_2.Text,
                                                   cboAccount_Manager.SelectedValue, cboAssigned_To.SelectedValue,
                                                   txtNotes.Text, cboCAT_Contract_Status_ID.SelectedValue,
                                                   userSite.UserId.ToString(),
                                                   string.IsNullOrEmpty(hidCreatedOn.Value) ? DateTime.Now.ToString() : hidCreatedOn.Value,
                                                   chkActive.Checked
                        );
                    hidId.Value = hidID;
                    

                    if (chkSendEmail.Checked)
                    {
                        var userManager = _siteUser;
                        var cc = gSDMS_BL.mp_User_Lst("12");
                        var assigned = gSDMS_BL.mp_User_get(cboAssigned_To.SelectedValue, null);
                        var emailFrom = userManager.Email;
                        var emailCc = "";
                        foreach (var p in cc)
                        {
                            var email = p.Email;
                            emailCc += email + ",";
                        }

                        var emailTo = assigned.Email;
                        string subject, textBody;
                        if (string.IsNullOrEmpty(id))
                        {
                            subject = string.Format("[CONTRACT-gSDMS]]WE HAVE A NEW CONTRACT : {0}", txtContract_Name.Text);
                            textBody = "Dear " + assigned.LoginName + "<br/><br/> We have a new contract : <b>" + txtContract_Name.Text + "</b>. <br/><br/> <b><u>Contract Code</b></u> : " + txtContract_Code.Text + "<br/><br/> <b><u>From customer</b></u> : " + txtCustomer_Name.Text + " (Code : " + txtCustomer_Code.Text + ")" +
                            " <br/><br/> <b><u>Note </b></u> : " + txtNotes.Text +
                            "<br/><br/> Please enter follow link to accept : " +  SiteRoot + "/gsdmsmodule/contract/Contract_Cat.aspx"
                            +  "<br/><br/> Regard,<br/> " + userManager.LoginName;
                        }
                        else
                        {
                            subject = string.Format("[CONTRACT-gSDMS]INFOMATION OF CONTRACT {0} HAS BEEN CHANGED", txtContract_Name.Text);
                            textBody = "Dear " + assigned.LoginName + "<br/><br/> The contract <b>" + txtContract_Name.Text + "</b> has been changed. <br/><br/> <b><u>Contract Code</b></u> : " + txtContract_Code.Text + 
                            " <br/><br/> <b><u>Note </b></u>: " + txtNotes.Text +
                            "<br/><br/> Please enter follow link to check :" + SiteRoot + "/gsdmsmodule/contract/Contract_Cat.aspx"
                             + "<br/><br/> Regard,<br/> " + userManager.LoginName;
                        }
                        var siteGuid = siteSettings.SiteGuid;
                        Library.SendMail(emailFrom, emailTo, emailCc, string.Empty, subject, textBody, siteGuid);
                        chkSendEmail.Checked = false;
                    }
                    

                    if (!string.IsNullOrEmpty(hidId.Value))
                    {
                        if (isUpload)
                        {
                            UploadFile();
                        }
                        lblMes.Text = @"Updated!";
                        lblMes.Visible = true;
                        
                    }
                    
                 if (string.IsNullOrEmpty(id))
                    Response.Redirect(@"/gsdmsmodule/contract/contract_cat.aspx");

            }
            catch (Exception ex)
            {
                lblMes.Text = ex.Message;
                lblMes.Visible = true;
            }
        }

        void datContract_Date_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {
            if (datContract_Date.SelectedDate != null)
            {
                datStart_Date.MinDate = (DateTime) datContract_Date.SelectedDate;
            }
        }

        void datStart_Date_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {
            if (datStart_Date.SelectedDate != null)
            {
                datEnd_Date.MinDate = (DateTime)datStart_Date.SelectedDate;
            }
        }
        void datEnd_Date_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {

        }

        void rptAttachments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + e.CommandArgument;
            path = path.Replace("/", "\\");
            switch (e.CommandName)
            {
                case "DeleteItem":
                    var repository = new ud_gSDMS_Attachments();
                    bool a = repository.DeleteItemAttachment(e.CommandArgument.ToString());
                    bool b = repository.Delete(e.CommandArgument.ToString());
                    if (a && b)
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                    break;
                case "DownloadItem":
                    {
                        var repository_ = new ud_gSDMS_Attachments();
                        var file = repository_.GetOne(Convert.ToInt32(e.CommandArgument));
                        path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + file.ServerFileName;

                        FileInfo f = new FileInfo(path);

                        if (f.Exists)
                        {

                            Response.Clear();
                            Response.ContentType = "application/octet-stream";
                            Response.AddHeader("Content-Disposition", "attachment; filename=" + Library.RemoveSign4VietnameseString(file.FileName).Replace(" ", "-"));
                            Response.WriteFile(path);
                            Response.End();
                            //if file does not exist
                        }
                        else
                        {
                            Response.Write("This file does not exist.");
                        }
                        break;
                    }

            }
            WebUtils.SetupRedirect(this, Request.RawUrl);
        }

        void rptAttachments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Image imgType = (Image)e.Item.FindControl("imgType");
            if (imgType == null) return;
            string name = DataBinder.Eval(e.Item.DataItem, "p.FileName", "{0}").Trim();
            // ReSharper disable PossibleNullReferenceException
            var imgFile = Path.GetExtension(name).ToLower().Replace(".", "") + ".png";
            var path = Request.PhysicalApplicationPath + "/Data/SiteImages/Icons/" + imgFile;
            if (File.Exists(path))
            {
                imgType.ImageUrl = ImageSiteRoot + "/Data/SiteImages/Icons/" + imgFile;
            }
            var ibtnDelete = (ImageButton)e.Item.FindControl("ibtnDelete");
            ud_Utilities.Utilities.AddConfirmButton(ibtnDelete, "Do you want to delete this file?");
        }

        void btnUpload_Click(object sender, EventArgs e)
        {
            UploadFile();
            //WebUtils.SetupRedirect(this, SiteRoot + article.ItemUrl.Replace("~/", "/"));
        }

        int UploadFile()
        {
            var upLoadPath = Page.Server.MapPath(WebUtils.GetApplicationRoot() + "/Data/gSDMSAttachments/");
            int fileID = 0;

            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            if (hidId.Value == "")
            {
                return 0;
            }
            //if (article == null) { WebUtils.SetupRedirect(this, Request.RawUrl); return; }
            //if ((article.ItemId <= 0) || (article.ModuleId != moduleId)) { WebUtils.SetupRedirect(this, Request.RawUrl); return; }
            if (file1.HasFile && file1.FileName != null && file1.FileName.Trim().Length > 0)
            {
                var repository = new ud_gSDMS_Attachments();

                string serverFileName = Guid.NewGuid() + ".config";

                var suss = repository.Create(file1.FileName, serverFileName, (int)(file1.ContentLength / 1024), out fileID, OptionForm.Contract.ToString(), hidId.Value);
                if (suss)
                {
                    var destPath = upLoadPath + serverFileName;

                    if (File.Exists(destPath))
                    {
                        File.Delete(destPath);

                    }
                    file1.MoveTo(destPath, MoveToOptions.Overwrite);
                }
                BindAttachments();
            }

            CacheHelper.TouchCacheDependencyFile(cacheDependencyKey);
            return fileID;
        }

        private void BindAttachments()
        {
            var repository = new ud_gSDMS_Attachments();
            var item = repository.GetByItemID(OptionForm.Contract.ToString(), hidId.Value);
            rptAttachments.DataSource = item;
            rptAttachments.DataBind();
            lblAttachments.Visible = rptAttachments.Items.Count > 0;
        }
        #endregion event

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);

            SiteUtils.SetupEditor(txtNotes);

            btnSave.Click+=new EventHandler(btnSave_Click);
            btnUpload.Click += btnUpload_Click;
            datContract_Date.SelectedDateChanged += datContract_Date_SelectedDateChanged;
            datStart_Date.SelectedDateChanged += datStart_Date_SelectedDateChanged;
            datEnd_Date.SelectedDateChanged += datEnd_Date_SelectedDateChanged;

            rptAttachments.ItemCommand += rptAttachments_ItemCommand;
            rptAttachments.ItemDataBound += rptAttachments_ItemDataBound;
            //btnFinish.Click += btnFinish_Click;
            SuppressPageMenu();
        }
      
        //void btnFinish_Click(object sender, EventArgs e)
        //{
        //    WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
        //}

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            id = WebUtils.ParseStringFromQueryString("id", id);
            cacheDependencyKey = "Module-" + moduleId.ToInvariantString();
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion
    }
}